package com.gljx.web.controller;

import com.gljx.util.GetFnumber;
import com.gljx.util.ImportExecl;
import com.gljx.util.TimeFormat;
import com.gljx.web.Entity.*;
import com.gljx.web.dao.StudentMapper;
import com.gljx.web.service.CustomLogService;
import com.gljx.web.service.DepartmentService;
import com.gljx.web.service.DropexerciseThreeService;
import com.gljx.web.service.CalculatetimecarsubService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by Administrator on 2017/11/20 0020.
 */
@Controller
@RequestMapping("/")
public class CalculatetimecarsubContraller {

   /* @Autowired
    DropexerciseThreeService dropexerciseThreeService;
    @Autowired
    DepartmentService departmentService;

    @Autowired
    ExerciseCarPlanController exerciseCarPlanController;

    @Autowired
    StudentController studentController;
    @Autowired
    PersonController personController;
    @Autowired
    StudentMapper studentMapper;*/

    @Autowired
    CustomLogService customLogService;
    @Autowired
    CalculatetimecarsubService salculatetimecarsubService;

    @RequestMapping("/queryCalculatetimecarsub")
    public String queryCalculatetimecarsub(HttpServletRequest request, @RequestParam(value = "cfstudentname", defaultValue = "") String cfstudentname
            , @RequestParam(value = "cfidcardno", defaultValue = "") String cfidcardno
            , @RequestParam(value = "cfmobile", defaultValue = "") String cfmobile
            , @RequestParam(value = "beginTime", defaultValue = "") String beginTime
            , @RequestParam(value = "endTime", defaultValue = "") String endTime) {
        PageBean<Sharecarsub> pb = new PageBean<>();
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        try {
            cfstudentname = cfstudentname.trim();//去空格
            cfidcardno = cfidcardno.trim();
            cfmobile = cfmobile.trim();
            //默认时间
            if ("".equals(beginTime) && "".equals(endTime)) {
                beginTime = TimeFormat.getMonth();
                endTime = TimeFormat.getNowTime();
            }
            if (cfstudentname != null && !cfstudentname.equals("") || cfidcardno != null && !cfidcardno.equals("") || cfmobile != null && !cfmobile.equals("")) {
                //页面搜索模糊查询
                //获取分页
                pb = getPageBean(request, user.getFcompanyid(), cfstudentname, cfidcardno, cfmobile, beginTime, endTime);
            } else {
                //获取分页  如果编码为空默认按照业务日期排序分页显示
                pb = getPageBean(request, user.getFcompanyid(), null, cfidcardno, cfmobile, beginTime, endTime);
            }
            //计数器
            int i = 0;
            //缓存需要删除的序列
            List<Integer> tem = new ArrayList<>();
            //获取当前分页的值
            List<Sharecarsub> calculatetimecarsubList = pb.getBeanList();
            //返回界面的搜索条件
            request.setAttribute("cfstudentname", cfstudentname);
            request.setAttribute("cfidcardno", cfidcardno);
            request.setAttribute("cfmobile", cfmobile);
            request.setAttribute("beginTime", beginTime);
            request.setAttribute("endTime", endTime);

            request.setAttribute("calculatetimecarsubList", calculatetimecarsubList);
            request.setAttribute("pb", pb);


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "/backHome/orderManage/calculatetimecarsubOrder/calculatetimecarsubOrderList";
    }

    public PageBean<Sharecarsub> getPageBean(HttpServletRequest request, String companyId, String cfstudentname,
                                             String cfidcardno, String cfmobile,
                                             String beginTime, String endTime) throws Exception {

        int offset;//从第几条数据开始加载
        if (request.getParameter("pager.offset") == null) {
            offset = 0;
        } else {
            offset = Integer.parseInt(request.getParameter("pager.offset"));
        }
        //拼接SQL语句
        StringBuffer psql = new StringBuffer();
        if (cfstudentname == null) {
            psql.append("SELECT T.FID, e.fname_l2 kmelcsj,e.fname_l2 kmslcsj,t.CFSUBJECT,t.CFSQZJCXDH,t.FNUMBER,s.FNUMBER xsfnumber,t.CFSTUDENTNAME, " +
                    "  t.CFVIP,t.CFSUBRESULT,t.CFMOBILE,t.CFPHONE,r.FNUMBER yyjlfnumber,t.CFCOACHNAME,t.CFREMARK,t.CFCARBYTE,to_char(t.CFNEXTTIME, 'YYYY-MM-DD') cfnexttime,t.CFARREARAGE, " +
                    "  c.FNAME_L2 classname,t.CFAMOUNT,t.CFRECEIVED,t.CFFAVORABLE,r1.FNAME_L2 yjlname, " +
                    "  to_char(t.CFKMEKSSJ, 'YYYY-MM-DD') cfkmekssj,to_char(t.CFKMSBJKSJ, 'YYYY-MM-DD') cfkmsbjksj,t.CFIDCARDNO,t.CFJBKCS,t.CFJBKFJE,t.CFKSCS " +
                    "  FROM CT_DS_CALCULATETIMECARSUB t LEFT JOIN ct_ds_student s ON s.fid = t.cfstudentid " +
                    "  LEFT JOIN ct_ds_exercisecarplan e ON e.fid = t.CFEXERCISECARPLANI " +
                    "  LEFT JOIN CT_DS_PERSON r ON r.fid = t.CFCOACHID " +
                    "  LEFT JOIN ct_ds_clazz c ON t.CFCLAZZID = c.fid " +
                    "  LEFT JOIN CT_DS_PERSON r1 ON t.CFOLDCOACHID = r1.FID");
            psql.append(" where t.FCONTROLUNITID= '" + companyId + "' AND (t.cfsubject = 3 OR t.cfsubject = 2) and" +
                    "  (t.FCREATETIME BETWEEN to_date('" + beginTime + "', 'YYYY/MM/DD') AND to_date('" + endTime + "', 'YYYY/MM/DD')) ORDER BY T.FCREATETIME DESC");

        } else {
            psql.append("SELECT T.FID, e.fname_l2 kmelcsj,e.fname_l2 kmslcsj,t.CFSUBJECT,t.CFSQZJCXDH,t.FNUMBER,s.FNUMBER xsfnumber,t.CFSTUDENTNAME, " +
                    "  t.CFVIP,t.CFSUBRESULT,t.CFMOBILE,t.CFPHONE,r.FNUMBER yyjlfnumber,t.CFCOACHNAME,t.CFREMARK,t.CFCARBYTE,to_char(t.CFNEXTTIME, 'YYYY-MM-DD') cfnexttime,t.CFARREARAGE, " +
                    "  c.FNAME_L2 classname,t.CFAMOUNT,t.CFRECEIVED,t.CFFAVORABLE,r1.FNAME_L2 yjlname, " +
                    "  to_char(t.CFKMEKSSJ, 'YYYY-MM-DD') cfkmekssj,to_char(t.CFKMSBJKSJ, 'YYYY-MM-DD') cfkmsbjksj,t.CFIDCARDNO,t.CFJBKCS,t.CFJBKFJE,t.CFKSCS " +
                    "  FROM CT_DS_CALCULATETIMECARSUB t LEFT JOIN ct_ds_student s ON s.fid = t.cfstudentid " +
                    "  LEFT JOIN ct_ds_exercisecarplan e ON e.fid = t.CFEXERCISECARPLANI " +
                    "  LEFT JOIN CT_DS_PERSON r ON r.fid = t.CFCOACHID " +
                    "  LEFT JOIN ct_ds_clazz c ON t.CFCLAZZID = c.fid " +
                    "  LEFT JOIN CT_DS_PERSON r1 ON t.CFOLDCOACHID = r1.FID");
            psql.append(" where t.FCONTROLUNITID= '" + companyId + "' AND (t.cfsubject = 3 OR t.cfsubject = 2) ");

            if (!"".equals(cfstudentname) && cfstudentname != null) {
                psql.append("and t.CFSTUDENTNAME LIKE '%" + cfstudentname + "%' ");
            }
            if (!"".equals(cfidcardno) && cfidcardno != null) {
                psql.append("and t.CFIDCARDNO LIKE '%" + cfidcardno + "%' ");
            }
            if (!"".equals(cfmobile) && cfmobile != null) {
                psql.append("and  t.CFMOBILE LIKE '%" + cfmobile + "%' ");
            }
            psql.append("and  (t.CFNEXTTIME BETWEEN to_date('" + beginTime + "', 'YYYY/MM/DD') AND to_date('" + endTime + "', 'YYYY/MM/DD')) ORDER BY t.FCREATETIME DESC");
        }

        int psize = 15; //每页显示数
        int pindex = offset / psize;//+1  页码从0开始
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = salculatetimecarsubService.selectPage(pindex, psql.toString(), psize);
        PageBean<Sharecarsub> pb = new PageBean<>();
        pb.setPc(pindex); //页码
        Map<String, Object> paramMapCount = getPageBeanCount(psql.toString()); //取记录总数
        pb.setTr((int) paramMapCount.get("Pcount")); //记录总数
        pb.setPs(psize);
        pb.setBeanList((List<Sharecarsub>) paramMap.get("v_cur")); //每页数据集
        return pb;
    }

/*    @RequestMapping(value = "/go_add_Calculatetimecarsub")
    public String goAddDropexercisethree(HttpServletRequest request) throws Exception {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        Department department = departmentService.queryAdminByFid(user.getFcompanyid());

        String number = customLogService.selectFunmber("CT_DS_SHARECARSUB",user.getFcompanyid());
        String fnumber = GetFnumber.fnumbers(number, "YYFC");

        //查询练车时间
        Map map3 = exerciseCarPlanController.getExerciseCarPlan(request, "", "", "0");
        //查询科目二考试学生
        Map map = studentController.getPageBeanAsEnrol(request, "", "", "0", TimeFormat.getMonth(), TimeFormat.getNowTime(), "fcyy", 2, "");
        //查询教练弹窗信息
        Map map1 = personController.getPageAsJl(request, "", "", "0");


        request.setAttribute("beginTime", TimeFormat.getMonth());
        request.setAttribute("endTime", TimeFormat.getNowTime());


        request.setAttribute("flag", "1");
        request.setAttribute("fbizdate", TimeFormat.getNowTime());
        request.setAttribute("createName", user.getName());
        request.setAttribute("fnumber", fnumber);
        request.setAttribute("department", department.getFnameL2());
        request.setAttribute("pb3", map3.get("pb"));
        request.setAttribute("exerciseCarPlans", map3.get("sList"));
        request.setAttribute("pb", map.get("pb"));
        request.setAttribute("students", map.get("sList"));
        request.setAttribute("pb1", map1.get("pb"));
        request.setAttribute("persons", map1.get("sList"));
        request.setAttribute("time", TimeFormat.getNowTime());

        return "/backHome/orderManage/practiseOrder/detailPractiseOrder";

    }

    @RequestMapping(value = "/add_Calculatetimecarsub")
    public String addSharecarsub(HttpServletRequest request, Sharecarsub calculatetimecarsub, String cflcsjid,
                                 @RequestParam(defaultValue = "0") String state) {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        //公司id
        calculatetimecarsub.setCfficompanyid(user.getFcompanyid());
        //控制单元id
        calculatetimecarsub.setFcontrolunitid(user.getFcompanyid());
        //获取当前修改时间
        String createTime = TimeFormat.timeFormat(new Date());
        //创建时间
        calculatetimecarsub.setFcreatetime(createTime);
        //创建人id
        calculatetimecarsub.setFcreatorid(user.getFid());


        //获取子类
        String[] zxsName = request.getParameterValues("zxsNameid");//学生id
        String[] zxsfnumber = request.getParameterValues("zxsfnumber");

        salculatetimecarsubService.addcalculatetimecarsub(calculatetimecarsub, zxsName, zxsfnumber, cflcsjid, state);


        //添加日志
        customLogService.addLog("练车管理", TimeFormat.timeFormat(new Date()) + "对科目二退练新增", null, user.getFid());


        return "redirect:/DrivingSys/go_add_Calculatetimecarsub";
    }

    @RequestMapping(value = "go_update_Calculatetimecarsub")
    public String goUpdateShareCarThreeReg(HttpServletRequest request, String fid, String state) throws Exception {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        Department department = departmentService.queryAdminByFid(user.getFcompanyid());

        //查询练车时间
        Map map3 = exerciseCarPlanController.getExerciseCarPlan(request, "", "", "0");
        //查询科目二考试学生
        Map map = studentController.getPageBeanAsEnrol(request, "", "", "0", TimeFormat.getMonth(), TimeFormat.getNowTime(), "fcyy", 2, "");
        //查询教练弹窗信息
        Map map1 = personController.getPageAsJl(request, "", "", "0");

        //查询模拟分车信息
        Sharecarsub calculatetimecarsub = salculatetimecarsubService.selectCalculatetimecarsubByFid(fid);
        List<Calculatetimecarsub> calculatetimecarsubList = salculatetimecarsubService.selectCalculatetimecarsubByFparentid(fid);

        request.setAttribute("beginTime", TimeFormat.getMonth());
        request.setAttribute("endTime", TimeFormat.getNowTime());

        request.setAttribute("flag", "2");
        request.setAttribute("calculatetimecarsub", calculatetimecarsub);
        request.setAttribute("calculatetimecarsubList", calculatetimecarsubList);
        request.setAttribute("department", department.getFnameL2());
        request.setAttribute("pb3", map3.get("pb"));
        request.setAttribute("exerciseCarPlans", map3.get("sList"));
        request.setAttribute("pb", map.get("pb"));
        request.setAttribute("students", map.get("sList"));
        request.setAttribute("pb1", map1.get("pb"));
        request.setAttribute("persons", map1.get("sList"));

        //如果是批量练车传入的界面 则保存 练车时间id
        if ("1".equals(state)) {
            request.setAttribute("cflcsjid", calculatetimecarsub.getCfexercisecarplani());
            return "/backHome/orderManage/practiseOrder/detailPractiseOrder1";
        }

        return "/backHome/orderManage/practiseOrder/detailPractiseOrder";
    }

    *//**
     * @Author lcx
     * @Date 2017/12/6 0006 下午 5:05
     * 删除
     *//*


    @RequestMapping(value = "/update_Sharecarsub")
    public String updateCalculatetimecarsub(HttpServletRequest request, Sharecarsub calculatetimecarsub, String cflcsjid, String state) throws Exception {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");

        //获取当前修改时间
        String createTime = TimeFormat.timeFormat(new Date());
        //修改时间
        calculatetimecarsub.setFlastupdatetime(createTime);
        //修改人id
        calculatetimecarsub.setFlastupdateuserid(user.getFid());

        //如果传入状态为5则代表审核
        if ("5".equals(calculatetimecarsub.getFfivouchered() + "")) {
            calculatetimecarsub.setFauditorid(user.getFid());
        }

        addSharecarsub(request, calculatetimecarsub, cflcsjid, "1");

        if ("1".equals(state)) {

            SharecarsubView calculatetimecarsubView = (SharecarsubView) request.getSession().getAttribute("calculatetimecarsubView");
            practiseOrderAdd(request, calculatetimecarsubView.getCfdycs(), cflcsjid, calculatetimecarsubView.getCfbilltype(), calculatetimecarsubView.getCfsqzjcxdh(), calculatetimecarsubView.getCfqty());

        }

        return "redirect:/DrivingSys/queryCalculatetimecarsub";
    }*/

    /**
     * @Author lcx
     * @Date 2018/1/12 0012 下午 1:48
     * 计时预约删除
     */
    @RequestMapping(value = "delete_Calculatetimecarsub")
    public String deleteCalculatetimecarsub(HttpServletRequest request, String[] deleteId) throws Exception {

        User user = (User) request.getSession().getAttribute("user");

        salculatetimecarsubService.deleteByCalculatetimecarsubKey(deleteId);
        //添加日志
        customLogService.addLog("预约管理", TimeFormat.timeFormat(new Date()) + "对练车微信预约进行删除", null, user.getFid());


        return "redirect:/DrivingSys/queryCalculatetimecarsub";
    }

    /**
     * 取记录总数 dmz 20160921
     *
     * @param psql SQL语句
     * @return Map
     * @throws Exception
     */
    public Map<String, Object> getPageBeanCount(String psql) throws Exception {

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = salculatetimecarsubService.selectPageCount(psql);
        return paramMap;
    }


}
